package com.xmkj.carwash.mine.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.entity.bean.UserDetailsBean;
import com.common.retrofit.entity.result.FaceBean;
import com.common.retrofit.entity.result.UpLoadPicEntity;
import com.common.retrofit.methods.UpdateUserMethods;
import com.common.retrofit.methods.UserInfoMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.SortUtils;
import com.common.widget.imageview.image.ImageLoaderUtils;
import com.common.widget.navigation.WidgetButton;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xmkj.carwash.R;
import com.xmkj.carwash.utils.BottomPickerUtils;
import com.xmkj.carwash.utils.CreateBmpFactory;
import com.xmkj.carwash.utils.GraphicsBitmapUtils;
import com.xmkj.carwash.utils.HandlerHelper;
import com.xmkj.carwash.utils.HttpURLConnHelper;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by chen on 2018/3/28.
 */

public class InfoCompileActivity extends BaseMvpActivity {
    @BindView(R.id.iv_face)
    ImageView mIvFace;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.iv_next)
    ImageView mIvNext;
    @BindView(R.id.tv_sex)
    TextView mTvSex;
    @BindView(R.id.rl_sex)
    RelativeLayout mRlSex;
    @BindView(R.id.iv_next1)
    ImageView mIvNext1;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.rl_date)
    RelativeLayout mRlDate;
    private String birth;
    private OptionsPickerView siteTypePicker;
    private List<String> siteTypeStrList = new ArrayList<>();
    private String person_sex;
    private UserDetailsBean info;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_compile_info;
    }

    @Override
    protected void onViewCreated() {
        setRightNavigationText();


    }

    @Override
    protected void doLogicFunc() {
        attachClickListener(mRlDate);
        attachClickListener(mRlSex);
        attachClickListener(mIvFace);
        initSexOptionsPicker();
        gotoGetUserInfo();


    }
    private void gotoGetUserInfo() {
        showProgressingDialog();
        CommonSubscriber<UserDetailsBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                info = (UserDetailsBean) o;

                setInfo();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        UserInfoMethods.getInstance().userInfo(subscriber,uid,hashid);
        rxManager.add(subscriber);
    }
    private void setInfo() {
        if(EmptyUtils.isNotEmpty(info)){
            if(EmptyUtils.isNotEmpty(info.face)){
                ImageLoaderUtils.displayCircle(mIvFace, info.face);
            }
            mEtName.setText(info.nickname);
            if(info.sex.equals("1")){
                mTvSex.setText("男");
                person_sex = "1";
            }else  if(info.sex.equals("2")){
                person_sex = "2";
                mTvSex.setText("女");
            }
            mTvDate.setText(info.birth);
            birth = info.birth;
        }


    }

    @Override
    protected void onViewClicked(View view) {
        if (view.getId() == mRlDate.getId()) {
            goChooseBirthDay();
        } else if (view.getId() == mRlSex.getId()) {
            if (siteTypePicker != null) {
                siteTypePicker.show();
            }
        }else if(view.getId()==mIvFace.getId()){
            if (mCreateBmpFactory == null) {
                mCreateBmpFactory = new CreateBmpFactory(this);
            }
            AndPermission.with(this)
                    .requestCode(105)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .rationale(mRationaleListener)
                    .send();
        }
    }

    private void setRightNavigationText() {
        m_navigationBar.setVisibility(View.VISIBLE);
        WidgetButton widgetButton = new WidgetButton(this, R.string.insure);
        widgetButton.getTextView().setTextColor(getResources().getColor(R.color.black));
        widgetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              if(EmptyUtils.isEmpty(getEditTextStr(mEtName))||EmptyUtils.isEmpty(person_sex)||EmptyUtils.isEmpty(birth)){
                    showToastMsg("请填写完整信息");
                    return;
                }
                gotoUpdateUser();
            }
        });
        m_navigationBar.setRightMenu(widgetButton);
    }

    private void gotoUpdateUser() {
        showProgressingDialog();
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.UPDATE_INFO, true));
                onBackPressed();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });


        UpdateUserMethods.getInstance().saveData(subscriber,uid,hashid,info.detail_id,getEditTextStr(mEtName),birth,face_id,person_sex);
        rxManager.add(subscriber);
    }

    private void goChooseBirthDay() {
        Calendar startTime = Calendar.getInstance();
        int year = startTime.get(Calendar.YEAR);    //获取年
        int month = startTime.get(Calendar.MONTH);   //获取月份，0表示1月份
        int day = startTime.get(Calendar.DAY_OF_MONTH);    //获取当前天数
        startTime.set(year, month, day);
        Calendar endTime = Calendar.getInstance();
        endTime.set(1930, 0, 1);
        Calendar selectTime = Calendar.getInstance();
        MyDatePickerRepaymentDate myDatePickerCallBack = new MyDatePickerRepaymentDate();
        BottomPickerUtils.showDatePicker(this, endTime, startTime, selectTime, myDatePickerCallBack);
    }

    private void initSexOptionsPicker() {
        siteTypeStrList.clear();
        siteTypeStrList.add("男");
        siteTypeStrList.add("女");

        siteTypePicker = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (options1 == 0) {
                    person_sex = "1";//男的
                } else if (options1 == 1) {
                    person_sex = "2";
                }
                mTvSex.setText(siteTypeStrList.get(options1));

            }
        }).setSubmitText(getString(R.string.insure)).
                setCancelText(getString(R.string.cacal)).
                build();
        siteTypePicker.setPicker(siteTypeStrList);
    }

    @Override
    protected void setNavigation() {
        setNavigationBack("信息编辑");
    }


    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    private class MyDatePickerRepaymentDate implements BottomPickerUtils.DatePickerCallback {

        @Override
        public void onDateSelect(Calendar calendar) {
            int year = calendar.get(Calendar.YEAR);    //获取年
            int month = calendar.get(Calendar.MONTH) + 1;   //获取月份，0表示1月份
            int day = calendar.get(Calendar.DAY_OF_MONTH);    //获取当前天数
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int min = calendar.get(Calendar.MINUTE);
            birth = year + "-" + month + "-" + day;
            mTvDate.setText(birth);
            System.out.println(year + "----------" + month + "月" + day + "日" + hour + "时" + min + "分钟");
        }
    }
    /*图片上传*/
    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(InfoCompileActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能使用相机，请把相机权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };
    //点击头像弹出popwindow
    private PicPopupWindow popupWindow;
    //存储头像
    private String filePath = "";
    private CreateBmpFactory mCreateBmpFactory;
    private Bitmap bmp;
    public static final int REQUEST_CODE_CAMERA = 1000;
    public static final int REQUEST_CODE_GALLERY = 1001;
    private TextView tv_cancel;
    private TextView tv_camera;
    private TextView tv_photo;
    public class PicPopupWindow extends PopupWindow {
        public PicPopupWindow(Context mContext, View parent) {
            View view = View.inflate(InfoCompileActivity.this, R.layout.pop_payback_select, null);
            tv_photo = (TextView) view.findViewById(R.id.tv_plan_repayment);//相册
            tv_photo.setText("相册");
            tv_camera = (TextView) view.findViewById(R.id.tv_plan_consume);//相机
            tv_camera.setText("相机");
            tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            tv_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            filePath = resultList.get(0).getPhotoPath();
                            bmp = mCreateBmpFactory.getBitmapByOpt(filePath);
//                            ivFace.setImageBitmap(bmp);
                            //上传头像
                            if (!"".equals(filePath)) {
//                                setPicToNet(bmp);
//                                ivFace.setImageBitmap(bmp);
                                ImageLoaderUtils.displayCircle(mIvFace,filePath);
                                setPicToNet(bmp);
                            }
                            popupWindow.dismiss();
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {

                        }
                    });
                }
            });
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            tv_photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            filePath = resultList.get(0).getPhotoPath();
                            bmp = mCreateBmpFactory.getBitmapByOpt(filePath);
                            //上传头像
                            if (!"".equals(filePath)) {
//                                ivFace.setImageBitmap(bmp);
                                ImageLoaderUtils.displayCircle(mIvFace,filePath);
                                setPicToNet(bmp);
                            }
                            popupWindow.dismiss();
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {

                        }
                    });
                }
            });
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_in_a));
            setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            showAsDropDown(view);
            setOutsideTouchable(true);
            setBackgroundDrawable(getResources().getDrawable(R.color.bg_title2));
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
        }
    }
    @PermissionYes(105)
    private void openPic() {
        popupWindow = new PicPopupWindow(this, mIvFace);
    }

    @PermissionNo(105)
    private void injectPic() {
        popupWindow.dismiss();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToNet(final Bitmap bmp) {
        showProgressingDialog();
        new Thread() {
            @Override
            public void run() {
                byte[] photodata = GraphicsBitmapUtils.Bitmap2Bytes(bmp);
                Map parameters = new HashMap();
                parameters.put("time", System.currentTimeMillis() + "");
                parameters.put("hash",  SortUtils.getMyHash("fileName"));
                parameters.put("apiId", Constans.ANDROID_APP_ID);
                parameters.put("terminal", "3");
                parameters.put("fileName", "uploadFile");
                try {
//                    LogUtil.d(HttpUrl.uploadFace + "       -------->" + parameters + "-------->" + filePath + "-------->" + photodata + "-------->" + "utf-8");
                    String s = HttpURLConnHelper.doPostSubmitBody("http://xmqp1802008.api.hzxmnet.com/admin/Upload/uploadPicture ", parameters, filePath, photodata, "utf-8");
                    if (s != null) {
                        Message message = new Message();
                        message.obj = s;
                        message.what = 888;
                        handler.sendMessage(message);
                    } else {
                        dismissProgressDialog();
//                        ToastCommom.createToastConfig().ToastShow(CompileInfoActivity.this, "网络开小差啦,请稍后重试", getResources().getColor(R.color.white));
                        showToastMsg("请稍等");
                    }

                } catch (Exception e) {
//                    LogUtil.e("上传图片---" + e);
                    dismissProgressDialog();
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }

    UpLoadPicEntity upLoadPicEntity = new UpLoadPicEntity();
    private String face_id = "";
    private HandlerHelper handler = new HandlerHelper(this) {
        @Override
        protected void handleMessage(Object reference, Message msg) {
            switch (msg.what) {

                case 888:
                    dismissProgressDialog();

                    if (msg.obj != null) {
                        String res = msg.obj.toString();
                        System.out.println("dsds"+res);
                        if (upLoadPicEntity != null) {
                            try {
                                upLoadPicEntity = new Gson().fromJson(msg.obj.toString(), upLoadPicEntity.getClass());
                                if ("000000".equals(upLoadPicEntity.Code)) {
                                    FaceBean faceBean = new FaceBean();
                                    faceBean = new Gson().fromJson(upLoadPicEntity.Data.data,faceBean.getClass());
                                    face_id = faceBean.lists.get(0).id+"";
                                    System.out.println("faceid"+face_id);
                                    //修改头像
//                                    circle_info_pic.setImageBitmap(bmp);
                                    //   GliderHelper.loadImage(filePath, circle_info_pic, null);
//                                    faceId = upLoadPicEntity.getData().getId() + "";
//                                    updataFace();
//                                    avatar = upLoadPicEntity.Data.avatar;
//                                    if(login_status==1){
//                                        SPUtils.setShareString(Constans.FACE_SHOPMAN,avatar);
//                                    }else if(login_status==2){
//                                        SPUtils.setShareString(Constans.FACE_SALES,avatar);
//                                    }
//                                    ImageLoaderUtils.display(ivAvatar,upLoadPicEntity.Data.path);
//                                    hash_choose_img = true;


                                } else {
                                    showToastMsg("请稍后再试");
                                    dismissProgressDialog();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
            }
        }
    };

}
